package com.xiaotu.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ScheduledService {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer count1 = 1;
    private Integer count2 = 1;
    private Integer count3 = 1;

    /**
     * 每10s执行一次定时任务
     */
    @Scheduled(fixedRate = 10000)//每隔10s执行一次任务
    public void scheduledTaskImmediately(){
        System.out.println(String.format("fixedRate第%s次执行,当前时间为:%s", count1++,dateFormat.format(new Date())));
    }
    @Scheduled(fixedDelay = 10000)//上一次任务执行结束后再在指定时间后继续执行
    public void scheduledTaskAfterSleep() throws Exception{
        System.out.println(String.format("fixedDelay第%s次执行,当前时间为:%s", count2++,dateFormat.format(new Date())));
        Thread.sleep(1000);//线程休眠1s
    }
    @Scheduled(cron = "0/10 * * * * *")
    public void scheduledTaskCron(){
        System.out.println(String.format("Cron第%s次执行,当前时间为:%s", count3++,dateFormat.format(new Date())));
    }
}
